<template>
  <div class="purchaser-profile">
    <el-card>
      <h2>个人信息</h2>
      <el-form :model="userInfo" label-width="120px">
        <el-form-item label="用户名">
          <span>{{ userInfo.username }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <el-tag :type="getRoleType(userInfo.role)">{{ getRoleText(userInfo.role) }}</el-tag>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="userInfo.phone" :disabled="!isEditing" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="userInfo.email" :disabled="!isEditing" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input type="textarea" v-model="roleDescription" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tag
            v-for="permission in getRolePermissions(userInfo.role)"
            :key="permission.name"
            type="info"
            effect="plain"
          >
            {{ permission.name }}
          </el-tag>
        </el-form-item>
      </el-form>
      <el-button 
        :type="isEditing ? 'primary' : 'default'" 
        @click="isEditing ? saveUserInfo() : startEditing()"
      >
        {{ isEditing ? '保存' : '修改' }}
      </el-button>
      <el-button v-if="isEditing" @click="cancelEditing">取消</el-button>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// 配置 axios 默认值
axios.defaults.baseURL = 'http://localhost:8000'
axios.defaults.timeout = 15000
axios.defaults.withCredentials = true

const userStore = useUserStore()
const userInfo = ref({
  username: '',
  role: '',
  phone: '',
  email: ''
})
const originalUserInfo = ref(null) // 保存原始数据，用于取消编辑
const roleDescription = ref('')
const isEditing = ref(false)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get('/api/users/profile/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    // 保存原始数据
    originalUserInfo.value = { ...response.data }
    
    userInfo.value = {
      ...response.data,
      role: response.data.role || 'purchaser'
    }
    roleDescription.value = getRoleDescription(userInfo.value.role)
    
    // 更新 store 中的用户信息
    userStore.setUser(response.data)
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户信息
const saveUserInfo = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 验证电子邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (userInfo.value.email && !emailRegex.test(userInfo.value.email)) {
      ElMessage.warning('请输入有效的电子邮箱地址')
      return
    }

    // 验证手机号格式（中国大陆手机号）
    const phoneRegex = /^1[3-9]\d{9}$/
    if (userInfo.value.phone && !phoneRegex.test(userInfo.value.phone)) {
      ElMessage.warning('请输入有效的手机号码')
      return
    }

    await axios.put('/api/users/me/update/', {
      email: userInfo.value.email,
      phone: userInfo.value.phone
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    // 重新获取最新的用户信息
    await fetchUserInfo()
    
    ElMessage.success('个人信息保存成功')
    isEditing.value = false
  } catch (error) {
    ElMessage.error('保存用户信息失败')
  }
}

// 开始编辑
const startEditing = () => {
  // 保存当前值，以便取消时恢复
  originalUserInfo.value = { ...userInfo.value }
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  // 恢复原始值
  userInfo.value = { ...originalUserInfo.value }
  isEditing.value = false
}

// 在组件挂载时获取用户信息
onMounted(async () => {
  await fetchUserInfo()
})

const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    purchaser: 'warning',
    salesman: 'success',
    deliveryman: 'info',
    customer: ''
  }
  return types[role] || ''
}

const getRoleText = (role) => {
  const texts = {
    admin: '系统管理员',
    purchaser: '采购员',
    salesman: '销售员',
    deliveryman: '配送员',
    customer: '客户'
  }
  return texts[role] || role
}

const getRoleDescription = (role) => {
  const descriptions = {
    admin: '系统管理员，负责整个系统的管理和维护。',
    purchaser: '采购员，负责商品采购和库存管理。',
    salesman: '销售员，负责订单处理和客户服务。',
    deliveryman: '配送员，负责商品配送和物流管理。',
    customer: '客户，可以浏览商品和下单。'
  }
  return descriptions[role] || ''
}

const getRolePermissions = (role) => {
  const permissions = {
    purchaser: [
      { name: '产品管理', description: '查看和管理产品信息' },
      { name: '采购订单', description: '创建和管理采购订单' }
    ]
  }
  return permissions[role] || []
}
</script>

<style scoped>
.purchaser-profile {
  padding: 24px;
}
</style>